package com.windbell.rest.security;


import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import com.fasterxml.jackson.databind.ObjectMapper;

import edu.fudan.langlab.domain.security.User;
import edu.fudan.langlab.domain.security.impl.UserImpl;
import windbell.domain.user.LoginService;

import static com.windbell.rest.security.SecurityConstants.*;

public class JWTAuthenticationFilter extends AbstractAuthenticationProcessingFilter{

	private LoginService loginService;

    public JWTAuthenticationFilter(LoginService loginService, AuthenticationSuccessHandler successHandler) {
    	super(new AntPathRequestMatcher("/login", "POST"));
    	this.setAuthenticationSuccessHandler(successHandler);
        this.loginService = loginService;
    }

	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, 
			HttpServletResponse response)
			throws AuthenticationException {
        try {
            User creds = new ObjectMapper()
                    .readValue(request.getInputStream(), UserImpl.class);
            User userEntity = loginService.login(creds.getUserid(), creds.getPasswd());
            if (userEntity != null){
            	request.setAttribute(CURRENT_USER_REQ, userEntity);
            	return new TokenBasedAuthentication(creds.getUserid());
            }
            throw new AuthenticationException("用户验证失败:" + creds.getUserid()){{}};
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
	}

}

